package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author mrchen
 * @date 2022/1/12 10:05
 */
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    public static final String APP_INFO_ARTICLE = "app_info_article";

    @Autowired
    EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    ApUserSearchService apUserSearchService;


    @Override
    public ResponseResult search(UserSearchDTO dto) {
        // 1. 校验参数  (searchWords)
        if (StringUtils.isBlank(dto.getSearchWords())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "搜索内容不能为空");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        dto.setEntryId(user==null?null:user.getId());
        // insert 是异步执行的方法，如果在insert中获取当前登录用户  是获取不到的
        apUserSearchService.insert(dto);

        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 2. 构建查询参数 SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 2.1  构建bool 条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //          使用 match 查询title ==>  must
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        //          使用 range 查询publish < minDate ==> filter
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        sourceBuilder.query(boolQueryBuilder);
        // 2.2   设置高亮条件   高亮字段:title    <span></span>
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);
        // 2.3   排序条件 按照发布时间降序排序
        sourceBuilder.sort("publishTime", SortOrder.DESC);
        // 2.4   分页条件  size:   每页条数
        sourceBuilder.size(dto.getPageSize());
        // 3.  调用search方法 执行搜索
        PageResponseResult result = esService.search(sourceBuilder, SearchArticleVO.class, APP_INFO_ARTICLE);
        // 4.  在结果上添加 静态页的访问前缀
        List<SearchArticleVO> list = (List<SearchArticleVO>) result.getData();
        for (SearchArticleVO searchArticleVO : list) {
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
        }
        return result;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,APP_INFO_ARTICLE);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,APP_INFO_ARTICLE);
    }
}